<!-- 录入凭证页面 -->
<template>
  <div class="padding">
    <el-card>
      <div class="text-right margin-bottom">
        <el-button-group>
          <el-button type="warning" size="mini" @click="addRow">
            新增行数
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="saveFinanceVoucher"
            ref="saveButton"
          >
            保存凭证
          </el-button>
        </el-button-group>
      </div>

      <div class="my_border">
        <div class="my_titile">记账凭证</div>
        <div class="flex justify-end">
          <div class="my_margin">
            <span class="margin-right">日期</span>
            <el-date-picker
              size="mini"
              v-model="accountDate"
              type="date"
              @change="findSelectMonthVoucherNo"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
          <div>
            <span class="margin-right">凭证号</span>
            <el-input
              size="mini"
              style="width: 100px"
              v-model="voucherNo"
              disabled
            ></el-input>
          </div>
        </div>
        <el-table
          border
          size="mini"
          class="text-sm"
          :data="tableData"
          :cell-style="{ 'text-align': 'center' }"
          :header-cell-style="{ 'text-align': 'center' }"
          :summary-method="getSummaries"
          show-summary
        >
          <el-table-column label="摘要" min-width="18%">
            <template slot-scope="scope">
              <div class="inputDeep" @dblclick="selectedTd(scope, 0)">
                <el-input
                  size="mini"
                  v-model="scope.row.digest"
                  @keyup.right.native="copyRow(scope.$index)"
                ></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="会计科目"
            prop="financeSubjectTd"
            min-width="30%"
            class-name="account-td"
          >
            <template slot-scope="scope">
              <el-row class="flex align-center">
                <el-col :span="12">
                  <div class="inputDeep" @dblclick="selectedTd(scope, 1)">
                    <!-- <el-input
                      size="mini"
                      v-model="scope.row.financeSubjectTd"
                    ></el-input> -->
                    <el-select
                      v-model="scope.row.financeSubjectTd"
                      filterable
                      remote
                      reserve-keyword
                      :remote-method="financeSubjectMap"
                      placeholder="请选择会计科目"
                    >
                      <el-option
                        v-for="(item, value) in financeSubjectSource"
                        :key="value"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </div>
                </el-col>
                <el-col :span="12" class="border-left">
                  <el-row>
                    <el-col :span="12">
                      <div class="inputDeep" @click="selectedTd(scope, 2)">
                        <el-input
                          size="mini"
                          v-model="scope.row.current"
                        ></el-input>
                      </div>
                    </el-col>
                    <el-col :span="12" class="inputDeep border-left">
                      <el-input size="mini" v-model="scope.row.rate"></el-input>
                    </el-col>
                  </el-row>
                  <div class="inputDeep border-top">
                    <el-input
                      size="mini"
                      v-model="scope.row.currentRateMoney"
                    ></el-input>
                  </div>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="往来单位" min-width="18%">
            <template slot-scope="scope">
              <div class="text-box pointer" @click="selectedTd(scope, 3)">
                <template
                  v-if="scope.row.withTheUnitType && scope.row.withTheUnitId"
                >
                  <template v-if="scope.row.withTheUnitType == 1">
                    {{ userSourceMap[scope.row.withTheUnitId] }}
                  </template>
                  <template v-else-if="scope.row.withTheUnitType == 2">
                    {{ customerMap[scope.row.withTheUnitId] }}
                  </template>
                  <template v-else-if="scope.row.withTheUnitType == 3">
                    {{ serveCompanyMap[scope.row.withTheUnitId] }}
                  </template>
                </template>
                <template v-else>
                  <span v-for="item in scope.row.departId" :key="item">
                    <template v-if="initData.organizationDepartmentSource">
                      {{ initData.organizationDepartmentSource[item] }}
                    </template>
                    <template v-else>
                      item
                    </template>
                  </span>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="借方金额" prop="debitMoney" min-width="16%">
            <template slot-scope="scope">
              <div
                class="inputDeep"
                @dblclick="calculateTheTotal(scope, 'debitMoney')"
              >
                <el-input
                  size="mini"
                  type="number"
                  v-model="scope.row.debitMoney"
                  @focus="
                    switchCreditDebitMoney(
                      scope,
                      'debitMoney',
                      scope.row.creditorMoney
                    )
                  "
                ></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="贷方金额"
            prop="creditorMoney"
            min-width="16%"
          >
            <template slot-scope="scope">
              <div
                class="inputDeep"
                @dblclick="calculateTheTotal(scope, 'creditorMoney')"
              >
                <el-input
                  type="number"
                  size="mini"
                  v-model="scope.row.creditorMoney"
                  @focus="
                    switchCreditDebitMoney(
                      scope,
                      'creditorMoney',
                      scope.row.debitMoney
                    )
                  "
                ></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label=" " prop="empty" width="100" min-width="2%">
            <template slot-scope="scope">
              <div class="btn-box">
                <el-button
                  @click="addRow({ scope })"
                  type="text"
                  class="text-xxl"
                  style="color: #000"
                  >＋
                </el-button>
                <el-button
                  type="text"
                  class="text-xxl"
                  style="color: #000"
                  @click="deleteRow(scope.$index, tableData)"
                  >－
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="margin-top" style="text-align: end">
          <span
            >制单:&nbsp;&nbsp;{{
              cuser ? userSourceMap[cuser] : $store.state.auth.user.name
            }}</span
          >
        </div>
      </div>
    </el-card>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :before-close="closeDialog"
    >
      <template v-if="selectedInput === 0">
        <el-tabs v-model="categoryActiveName" type="card">
          <el-tab-pane
            v-for="(item, value) in initData.financeCategoryVOS"
            :key="value"
            :label="value"
            :name="value"
          >
            <div class="padding">
              <el-radio-group v-model="radio" @change="changeRadio">
                <el-radio v-for="r in item" :key="r" :label="r"></el-radio>
              </el-radio-group>
            </div>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template v-else-if="selectedInput === 1">
        <el-tabs v-model="subjectTypeName" type="card">
          <el-tab-pane
            v-for="(item, value) in initData.subjectTypeDataMapJson"
            :key="value"
            :label="m(initData.financeSubjectTypeSourceMap[value])"
            :name="value"
          >
            <el-tree
              :data="item"
              :props="defaultProps"
              @node-click="handleNodeClick"
            >
            </el-tree>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template v-else-if="selectedInput === 2">
        <el-table
          ref="singleTable"
          size="mini"
          :data="initData.configCurType"
          highlight-current-row
          @current-change="handleCurrentChange"
        >
          <el-table-column prop="currency" label="币种"></el-table-column>
          <el-table-column prop="exchangeRate" label="汇率"></el-table-column>
          <el-table-column prop="useDate" label="使用期间"></el-table-column>
        </el-table>
      </template>
      <template v-else-if="selectedInput === 3">
        <template
          v-if="
            financeSubjectWithTheUnitTypes &&
              financeSubjectWithTheUnitTypes.length > 0
          "
        >
          <template v-if="financeSubjectWithTheUnitTypes.includes(1)">
            <el-row :gutter="10" class="flex align-center">
              <el-col :span="2">员工：</el-col>
              <el-col :span="20">
                <el-select
                  v-model="userId"
                  placeholder="请输入关键字搜索"
                  size="mini"
                  clearable
                  filterable
                  remote
                  :remote-method="remoteUser"
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="item in userNameOptions"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-col>
            </el-row>
          </template>
          <template v-if="financeSubjectWithTheUnitTypes.includes(2)">
            <el-row
              :gutter="10"
              class="flex align-center"
              style="margin-top: 10px;"
            >
              <el-col :span="2">客户：</el-col>
              <el-col :span="20">
                <el-select
                  v-model="customerId"
                  placeholder="请输入关键字搜索"
                  size="mini"
                  clearable
                  filterable
                  remote
                  :remote-method="remoteCustomer"
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="item in customerIdOptions"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-col>
            </el-row>
          </template>
          <template v-if="financeSubjectWithTheUnitTypes.includes(3)">
            <el-row
              :gutter="10"
              class="flex align-center"
              style="margin-top: 10px;"
            >
              <el-col :span="2">服务商：</el-col>
              <el-col :span="20">
                <el-select
                  v-model="serviceId"
                  placeholder="请输入关键字搜索"
                  size="mini"
                  clearable
                  filterable
                  remote
                  :remote-method="remoteServicerCompany"
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="item in serviceCompanyOptions"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-col>
            </el-row>
          </template>
          <template v-if="financeSubjectWithTheUnitTypes.includes(0)">
            <el-row
              :gutter="10"
              class="flex align-center"
              style="margin-top: 10px;"
            >
              <el-col :span="2">部门：</el-col>
              <el-col :span="20">
                <el-select
                  v-model="departId"
                  multiple
                  filterable
                  placeholder="请选择"
                  size="mini"
                >
                  <el-option
                    v-for="(item, val) in initData.organizationDepartmentSource"
                    :key="val"
                    :label="item"
                    :value="parseInt(val)"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="2">
                <el-link @click="selectAll">全选</el-link>
              </el-col>
            </el-row>
          </template>
        </template>
        <template v-else>
          请先选择会计科目，并且给科目配置往来单位，没有配置往来单位的不允许选择
        </template>
      </template>
      <span slot="footer" class="dialog-footer" v-if="selectedInput === 3">
        <el-button size="mini" @click="cancelSelect">取 消</el-button>
        <el-button size="mini" type="primary" @click="enterSelect">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  ajax,
  searchCustomerLimit,
  searchServiceCompany,
  searchUser
} from "@/store/yg/common/utils";
import { m } from "@/store/yg/common/local";
import { Loading } from "element-ui";
import { clone } from "@/utils/clone";
import { checkRowsEmpty, parseTime } from "@/utils";
export default {
  data() {
    return {
      customerIdOptions: [],
      userNameOptions: [],
      serviceCompanyOptions: [],
      initData: {},
      cuser: "",
      dialogTitle: "",
      //需要删除的 凭证详情的 ids
      delFinanceVoucherDetails: [],
      categoryActiveName: "first",
      subjectTypeName: "first",
      dialogVisible: false,
      selectedTdIndex: 0,
      selectedInput: 0,
      accountDate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
      oleAccountDate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
      accountMonth: parseTime(new Date().toLocaleDateString(), "{y}-{m}"),
      voucherNo: 1,
      sign: "",
      radio: "",
      departId: [],
      customerId: null,
      serviceId: null,
      userId: null,
      search: {
        abstract: "",
        subjects: "",
        share: "",
        debit: "",
        credit: ""
      },
      financeSubject: {
        name: "" //远程搜索
      },
      tableData: [
        {
          digest: "", // 摘要
          financeSubjectTd: "", //会计科目
          current: "", //币种
          rate: "", // 汇率
          currentRateMoney: "",
          departId: [], // 分摊部门
          serOrCusId: "", //客户或者服务商ID,应收账款=客户ID,应付账款=服务商ID
          withTheUnitType: "", //往来单位类型
          withTheUnitId: "", //往来单位ID
          debitMoney: "", // 借方金额
          creditorMoney: "" //贷方金额
        },
        {
          digest: "", // 摘要
          financeSubjectTd: "", //会计科目
          current: "", //币种
          rate: "", // 汇率
          currentRateMoney: "",
          departId: [], // 分摊部门
          serOrCusId: "", //客户或者服务商ID,应收账款=客户ID,应付账款=服务商ID
          withTheUnitType: "", //往来单位类型
          withTheUnitId: "", //往来单位ID
          debitMoney: "", // 借方金额
          creditorMoney: "" //贷方金额
        },
        {
          digest: "", // 摘要
          financeSubjectTd: "", //会计科目
          current: "", //币种
          rate: "", // 汇率
          currentRateMoney: "",
          departId: [], // 分摊部门
          serOrCusId: "", //客户或者服务商ID,应收账款=客户ID,应付账款=服务商ID
          withTheUnitType: "", //往来单位类型
          withTheUnitId: "", //往来单位ID
          debitMoney: "", // 借方金额
          creditorMoney: "" //贷方金额
        },
        {
          digest: "", // 摘要
          financeSubjectTd: "", //会计科目
          current: "", //币种
          rate: "", // 汇率
          currentRateMoney: "",
          departId: [], // 分摊部门
          serOrCusId: "", //客户或者服务商ID,应收账款=客户ID,应付账款=服务商ID
          withTheUnitType: "", //往来单位类型
          withTheUnitId: "", //往来单位ID
          debitMoney: "", // 借方金额
          creditorMoney: "" //贷方金额
        },
        {
          digest: "", // 摘要
          financeSubjectTd: "", //会计科目
          current: "", //币种
          rate: "", // 汇率
          currentRateMoney: "",
          departId: [], // 分摊部门
          serOrCusId: "", //客户或者服务商ID,应收账款=客户ID,应付账款=服务商ID
          withTheUnitType: "", //往来单位类型
          withTheUnitId: "", //往来单位ID
          debitMoney: "", // 借方金额
          creditorMoney: "" //贷方金额
        }
      ],
      defaultProps: {
        children: "financeSubjectNodes",
        label: "label"
      },
      customerMap: {},
      serveCompanyMap: {},
      userSourceMap: {},
      dealingsObjectMap: {},
      financeSubjectSource: {}, //会计科目
      financeSubjectWithTheUnitTypes: [],
      totalMoney: ""
    };
  },
  computed: {
    tableTotal() {
      let totalDebitMoney = 0; //借方金额总计
      let totalCreditorMoney = 0; // 贷方金额总计
      for (const i of this.tableData) {
        if (!isNaN(parseFloat(i.debitMoney))) {
          totalDebitMoney =
            (Number(totalDebitMoney) * 1000 + parseFloat(i.debitMoney) * 1000) /
            1000;
        }
        if (!isNaN(parseFloat(i.creditorMoney))) {
          totalCreditorMoney =
            (Number(totalCreditorMoney) * 1000 +
              parseFloat(i.creditorMoney) * 1000) /
            1000;
        }
      }
      totalDebitMoney = totalDebitMoney.toFixed(2);
      totalCreditorMoney = totalCreditorMoney.toFixed(2);
      console.log("totalDebitMoney :>> ", totalDebitMoney);
      console.log("totalCreditorMoney :>> ", totalCreditorMoney);
      return {
        totalDebitMoney,
        totalCreditorMoney
      };
    }
  },

  mounted() {
    this.init();
  },

  methods: {
    async remoteCustomer(query) {
      if (query !== "") {
        this.customerIdOptions = await searchCustomerLimit(query);
      } else {
        this.customerIdOptions = [];
      }
    },
    async remoteServicerCompany(query) {
      if (query !== "") {
        this.serviceCompanyOptions = await searchServiceCompany(query);
      } else {
        this.serviceCompanyOptions = [];
      }
    },
    async remoteUser(query) {
      if (query != "") {
        this.userNameOptions = await searchUser(query);
      } else {
        this.userNameOptions = [];
      }
    },
    findSelectMonthVoucherNo() {
      ajax("getLasterVoucherNoByTime", { accountDate: this.accountDate }).then(
        res => {
          if (res.code != 200) {
            this.$message.error(res.message);
          } else {
            this.voucherNo = res.data;
          }
        },
        error => {
          console.log(error);
        }
      );

      //获取选择月份汇率
      ajax("queryFinanceAccountRate", { accountDate: this.accountDate }).then(
        res => {
          let data = res.data;
          let configCurArr = [];
          console.log(this.accountDate);
          Object.keys(data).forEach(key => {
            configCurArr.push({
              currency: key,
              exchangeRate: data[key],
              useDate: this.accountDate.substring(0, 7).replace("-", "/")
            });
          });
          this.initData.configCurType = configCurArr;
          let currencyMap = {};
          configCurArr.map(obj => {
            currencyMap[obj.currency] = obj;
          });
          console.log("currencyMap", currencyMap);
          this.tableData.forEach(row => {
            // 汇率重新选择,借货方金额重新计算
            row["rate"] = currencyMap[row.current].exchangeRate;

            if (row["debitMoney"] && row["rate"] && row["currentRateMoney"]) {
              row["debitMoney"] = (
                (row["rate"] * 100 * (row["currentRateMoney"] * 100)) /
                10000
              ).toFixed(2);
            } else if (
              row["creditorMoney"] &&
              row["rate"] &&
              row["currentRateMoney"]
            ) {
              row["creditorMoney"] = (
                (row["rate"] * 100 * (row["currentRateMoney"] * 100)) /
                10000
              ).toFixed(2);
            }
          });
        },
        error => {
          console.log(error);
        }
      );
    },
    calculateTheTotal(scope, type) {
      // debitMoney
      let total = 0;
      if (type === "debitMoney") {
        total = clone(this.tableTotal.totalCreditorMoney);
      } else {
        total = clone(this.tableTotal.totalDebitMoney);
      }

      let num = 0;
      for (const i in this.tableData) {
        num = (num * 1000 + Number(this.tableData[i][type]) * 1000) / 1000;
      }

      let totalMoney = (total * 1000 - num * 1000) / 1000;

      if (scope.row[type]) {
        totalMoney =
          (totalMoney * 1000 + Number(scope.row[type]) * 1000) / 1000;
      }

      this.$delete(scope.row, type);
      this.$set(scope.row, type, totalMoney.toFixed(2));
    },
    copyRow(row) {
      if (row > 0 && this.tableData[row - 1].digest) {
        this.$delete(this.tableData[row], "digest");
        this.$set(
          this.tableData[row],
          "digest",
          this.tableData[row - 1].digest
        );
      }
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计:"
          sums[1] =  this.digitUppercase(this.tableTotal.totalDebitMoney);
          return;
        }
        switch (
          column.property // column.property可以匹配它的每一列的命名， 然后赋值
        ) {
          case "debitMoney":
            sums[index] = this.tableTotal.totalDebitMoney; //值取自后台
            break;
          case "creditorMoney":
            sums[index] = this.tableTotal.totalCreditorMoney; //值取自后台
            break;

          default:
            break;
        }
      });

      return sums;
    },
    switchCreditDebitMoney(scope, type, money) {
      this.autoCount(scope, type);
      console.log("money", money);
      // if (scope.row.rate && scope.row.currentRateMoney) {
      //   const count = (
      //     (scope.row.currentRateMoney * 100 * (scope.row.rate * 100)) /
      //     10000
      //   ).toFixed(2);
      // debugger
      console.log("type", type);
      if (!money) {
        // this.$message.warning("单击有值的单元格转换借货方金额");
        return;
      }

      if (type === "debitMoney") {
        // debitMoney
        this.$set(scope.row, "creditorMoney", "");
        this.$set(scope.row, "debitMoney", money);
      } else {
        // creditorMoney
        this.$set(scope.row, "creditorMoney", money);
        this.$set(scope.row, "debitMoney", "");
      }
    },
    autoCount(scope, type, money) {
      // if (scope.row["debitMoney"] || scope.row["creditorMoney"]) {
      //   return;
      // }
      if (scope.row.rate && scope.row.currentRateMoney) {
        const count = (
          (scope.row.currentRateMoney * 100 * (scope.row.rate * 100)) /
          10000
        ).toFixed(2);
        if (type === "debitMoney") {
          // debitMoney
          let temDebitMoney = scope.row.debitMoney;
          this.$set(scope.row, "debitMoney", count);
          this.$set(scope.row, "creditorMoney", "");
        } else {
          // creditorMoney
          let temCreditorMoney = scope.row.creditorMoney;
          this.$set(scope.row, "debitMoney", "");
          this.$set(scope.row, "creditorMoney", count);
        }
      }
    },
    m(k) {
      return m(k);
    },
    digitUppercase(n) {
      if(!n) return
      var fraction = ["角", "分"];
      var digit = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
      var unit = [
        ["元", "万", "亿"],
        ["", "拾", "佰", "仟"]
      ];
      var head = n < 0 ? "欠" : "";
      n = Math.abs(n);
      var s = "";
      for (var i = 0; i < fraction.length; i++) {
        s += (
          digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]
        ).replace(/零./, "");
      }
      s = s || "整";
      n = Math.floor(n);
      for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = "";
        for (var j = 0; j < unit[1].length && n > 0; j++) {
          p = digit[n % 10] + unit[1][j] + p;
          n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, "").replace(/^$/, "零") + unit[0][i] + s;
      }
      return (
        head +
        s
          .replace(/(零.)*零元/, "元")
          .replace(/(零.)+/g, "零")
          .replace(/^整$/, "零元整")
      );
    },
    //远程搜索会计科目
    async financeSubjectMap(val) {
      this.financeSubject.name = val;
      ajax("remoteSearchSubject", this.financeSubject).then(
        res => {
          if (res.code != 200) {
            this.$message.error(res.message);
          } else {
            this.financeSubjectSource = res.data;
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    async init() {
      const { code, data, message } = await ajax("saveEditInit", {});
      if (code !== 200) {
        if (message) {
          this.$message.error(message);
        } else {
          this.$message.error("服务器异常");
        }
      }
      const configCurType = [];
      for (const i in data.configCurType) {
        configCurType.push({
          currency: i,
          exchangeRate: data.configCurType[i],
          useDate: new Date().toLocaleDateString().slice(0, 6)
        });
      }
      const parentAndSubMap = [];
      for (const i in data.parentAndSubMap) {
        let obj = {
          name: i,
          label: i
        };
        for (const j of data.parentAndSubMap[i]) {
        }
        parentAndSubMap.push(obj);
      }
      const categoryList = [];
      const subjectTypeList = [];
      for (const i in data.financeCategoryVOS) {
        categoryList.push(i);
      }
      for (const i in data.subjectTypeDataMapJson) {
        subjectTypeList.push(i);
        this.sortData(data.subjectTypeDataMapJson[i]);
      }

      this.userSourceMap = data.userSourceMap;
      this.customerMap = data.customerMap;
      this.serveCompanyMap = data.serveCompanyMap;
      this.dealingsObjectMap = data.dealingsObjectMap;
      this.initData.configCurType = configCurType;
      this.initData.parentAndSubMap = parentAndSubMap;
      this.initData.organizationDepartmentSource =
        data.organizationDepartmentSource;
      this.initData.subjectTypeDataMapJson = data.subjectTypeDataMapJson;
      this.initData.financeCategoryVOS = data.financeCategoryVOS;
      this.initData.financeSubjectTypeSourceMap =
        data.financeSubjectTypeSourceMap;
      this.categoryActiveName = categoryList[0];
      this.subjectTypeName = subjectTypeList[0];
      this.voucherNo = data.voucherNo;
      if (this.$route.query.pid) {
        this.getInfo(this.$route.query.pid);
      }
    },

    sortData(data) {
      for (const j of data) {
        j.label = j.financeSubject.no + " " + j.financeSubject.name;
        if (
          Object.prototype.toString.call(j.financeSubjectNodes) ===
          "[object Array]"
        ) {
          this.sortData(j.financeSubjectNodes);
        }
      }
      return data;
    },

    deleteRow(index, rows) {
      console.log("rows :>> ", rows);
      if (rows.length === 1) {
        return;
      }
      this.delFinanceVoucherDetails.push(rows[index].id);
      rows.splice(index, 1);
      console.log("delFinanceVoucherDetails", this.delFinanceVoucherDetails);
    },
    addRow({ scope }) {
      let newValue = {
        digest: "", // 摘要
        financeSubjectTd: "", //会计科目
        current: "", //币种
        rate: "", // 汇率
        currentRateMoney: "",
        departId: [], // 分摊部门
        serOrCusId: "", //客户或者服务商ID,应收账款=客户ID,应付账款=服务商ID
        withTheUnitType: "", //往来单位类型
        withTheUnitId: "", //往来单位ID
        debitMoney: "", // 借方金额
        creditorMoney: "" //贷方金额
      };

      if (scope) {
        this.tableData.splice(scope.$index + 1, 0, newValue);
      } else {
        this.tableData.push(newValue);
      }
    },
    selectedTd(scope, index) {
      console.log("scope :>> ", scope);
      this.selectedTdIndex = scope.$index;
      this.selectedInput = index;
      this.dialogVisible = true;
      let financeSubjectTd = scope.row.financeSubjectTd;
      switch (index) {
        case 0:
          this.dialogTitle = "请选择摘要";
          break;
        case 1:
          this.dialogTitle = "请选择科目";
          break;
        case 2:
          this.dialogTitle = "请选择币种汇率";
          break;
        case 3:
          this.dialogTitle = "请选择往来单位";
          console.log(financeSubjectTd);
          if (financeSubjectTd) {
            let financeSubjectNo = financeSubjectTd.slice(
              0,
              financeSubjectTd.indexOf(" ")
            );
            this.financeSubjectWithTheUnitTypes = this.dealingsObjectMap[
              financeSubjectNo
            ];
            if (scope.row.departId) {
              console.log("scope.row.departId :>> ", scope.row.departId);
              this.departId = scope.row.departId;
            }
          } else {
            this.financeSubjectWithTheUnitTypes = [];
          }
          break;
      }
    },
    handleNodeClick(d, n, l) {
      if (d.financeSubjectNodes) {
        return;
      }
      this.dialogVisible = false;

      this.tableData[this.selectedTdIndex].financeSubjectTd = d.label;

      if (
        d.label.indexOf("6603") == 0 &&
        this.tableData[this.selectedTdIndex].departId &&
        this.tableData[this.selectedTdIndex].departId.length === 0
      ) {
        this.tableData[this.selectedTdIndex].departId = [81];
      }
    },
    selectAll() {
      let arr = [];
      for (const i in this.initData.organizationDepartmentSource) {
        arr.push(parseInt(i));
      }
      this.departId = arr;
    },
    enterSelect() {
      console.log(
        this.customerId +
          "," +
          this.serviceId +
          "," +
          this.userId +
          "," +
          this.departId
      );
      let selectNum = 0;
      if (this.departId && this.departId.length > 0) {
        selectNum++;
      }
      if (this.customerId) {
        selectNum++;
      }
      if (this.serviceId) {
        selectNum++;
      }
      if (this.userId) {
        selectNum++;
      }
      if (selectNum > 1) {
        this.$message.error("往来单位只能选择一个单位录入！");
        return;
      }
      this.dialogVisible = false;
      let withTheUnitType = null;
      let withTheUnitId;
      if (this.departId && this.departId.length > 0) {
        this.tableData[this.selectedTdIndex].departId = this.departId;
        withTheUnitType = 0;
      } else if (this.customerId) {
        withTheUnitType = 2;
        withTheUnitId = this.customerId;
      } else if (this.serviceId) {
        withTheUnitType = 3;
        withTheUnitId = this.serviceId;
      } else if (this.userId) {
        withTheUnitType = 1;
        withTheUnitId = this.userId;
      }
      if (null != withTheUnitType) {
        this.tableData[this.selectedTdIndex].withTheUnitType = withTheUnitType;
      }
      if (withTheUnitId) {
        this.tableData[this.selectedTdIndex].withTheUnitId = withTheUnitId;
      }
      this.departId = [];
      this.customerId = null;
      this.serviceId = null;
      this.userId = null;
    },
    cancelSelect() {
      this.dialogVisible = false;
      this.departId = [];
    },
    closeDialog(done) {
      this.departId = [];
      this.radio = "";
      done();
    },
    handleCurrentChange(val) {
      if (val) {
        this.dialogVisible = false;
        this.tableData[this.selectedTdIndex].current = val.currency;
        this.tableData[this.selectedTdIndex].rate = val.exchangeRate;
        this.$refs.singleTable.setCurrentRow();
      }
    },
    changeRadio() {
      this.dialogVisible = false;
      this.tableData[this.selectedTdIndex].digest = this.radio;
    },

    /**
     * 保存凭证
     * */
    async saveFinanceVoucher() {
      const financeVoucherDetails = [];
      const hotTable = this.tableData.filter(x => x.financeSubjectTd !== "");

      if (hotTable.length === 0) {
        this.$message.error("请填写数据！");
        return;
      }
      //防止重复点击生成多条相同记录
      this.$refs["saveButton"].disabled = true;
      let loadingInstance = Loading.service();
      for (const i of hotTable) {
        console.log("i.financeSubjectTd :>> ", i.financeSubjectTd);
        let obj = {
          id: i.id || "",
          digest: i.digest,
          financeSubjectNo: i.financeSubjectTd
            ? i.financeSubjectTd.slice(0, i.financeSubjectTd.indexOf(" "))
            : "",
          current: i.current,
          rate: i.rate,
          serOrCusId: i.serOrCusId,
          withTheUnitType: i.withTheUnitType,
          withTheUnitId: i.withTheUnitId,
          currentRateMoney: i.currentRateMoney,
          debitMoney: i.debitMoney,
          creditorMoney: i.creditorMoney,
          financeVoucherSubjectDeparts: []
        };
        if (i.departId) {
          for (const j of i.departId) {
            obj.financeVoucherSubjectDeparts.push({
              departId: j
            });
          }
        }
        financeVoucherDetails.push(obj);
      }
      if (Number(this.tableTotal.totalCreditorMoney) === 0) {
        this.tableTotal.totalCreditorMoney = 0.0;
      }
      let info = {
        accountDate: this.accountDate,
        accountMonth: this.accountMonth,
        voucherNo: this.voucherNo,
        totalDebitMoney: this.tableTotal.totalDebitMoney,
        totalCreditorMoney: this.tableTotal.totalCreditorMoney,
        financeAccountNos: [],
        financeVoucherDetails: financeVoucherDetails
      };
      if (this.$route.query.pid) {
        info.id = this.$route.query.pid;
      }
      if (this.$route.query.financeAccountNo) {
        info.financeAccountNos.push(this.$route.query.financeAccountNo);
      }
      //需要删除的凭证的id
      info.delFinanceVoucherDetails = this.delFinanceVoucherDetails;

      let attrs = {};
      attrs["headers"] = {
        "YG-UNIQUE-KEY": "saveFinanceVoucher_" + new Date().getTime()
      };

      const { code, message, data2 } = await ajax(
        "saveFinanceVoucher",
        info,
        attrs
      );
      this.$nextTick(() => {
        // 以服务的方式调用的 Loading 需要异步关闭
        loadingInstance.close();
      });
      if (code === 200) {
        this.$message({
          type: "success",
          message: "保存成功！凭证号：" + data2
        });
        window.open("/#/main/finance__voucher__list", "_self");
      } else {
        if (message) {
          this.$message.error(message);
        } else {
          this.$message.error("服务器异常");
        }
      }
      this.$refs["saveButton"].disabled = false;
    },

    async getInfo(id) {
      const params = {};
      params["id"] = id;
      console.log(params);
      const { code, data, data2, message } = await ajax(
        "viewFinanceVoucher",
        params
      );
      if (code === 200) {
        //赋值上面的时间
        this.accountDate = data.accountDate;
        this.voucherNo = data.voucherNo;
        this.cuser = data.cuser;
        // financeSubjectTd
        // departId
        if (data.financeVoucherDetails) {
          for (const i of data.financeVoucherDetails) {
            i.departId = i.departList;
            i.financeSubjectTd =
              i.financeSubjectNo + " " + (data2[i.financeSubjectNo] || "");
          }
          //借方金额科目放在上面
          // data.financeVoucherDetails.map((currentValue, index, arr) => {
          //   if (currentValue["debitMoney"]) {
          //     arr.splice(index, 1);
          //     arr.splice(0, 0, currentValue);
          //   }
          // });

          this.tableData = data.financeVoucherDetails;
        } else {
          this.$message.error("凭证详情初始化失败");
        }
      } else {
        if (message) {
          this.$message.error(message);
        } else {
          this.$message.error("服务器异常");
        }
      }
    }
  }
};
</script>

<style scoped>
.my_border {
  margin: 0 auto;
  border: 1px solid #ccc;
  padding: 20px;
}

.my_titile {
  text-align: center;
  height: 30px;
  line-height: 30px;
  font-size: 24px;
  margin-bottom: 20px;
}

.my_margin {
  margin-right: 388px;
  margin-bottom: 20px;
}

.inputDeep >>> .el-input__inner {
  border: 0;
}

/deep/ .el-table tbody tr:hover > td {
  background-color: #fff;
}

/deep/ .el-table--mini td,
.el-table--mini th {
  padding: 0;
}

/deep/ .btn-box .el-button {
  padding: 0;
}

/deep/ .el-dialog__body {
  padding-top: 10px;
}

/deep/ .cell,
.el-select {
  width: 100%;
}

/deep/ .account-td .cell {
  padding-right: 0;
}
</style>
<style lang="scss" scoped>
.border-left {
  border-left: 1px solid #ebeef5;
}

.border-top {
  border-top: 1px solid #ebeef5;
}

.text-box {
  width: 100%;
  min-height: 28px;
}

.table-box {
  background-color: ghostwhite;
  width: 100%;
  padding: 15px;
}
</style>
